package org.fitweb.fixture;

import fit.ColumnFixture;
import fit.Parse;
import org.fitweb.drivers.BrowserController;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public abstract class FieldsFixture extends ColumnFixture {

    public String name;
    public String value;

    private BrowserController controller;


    public static FieldsFixture setFields(BrowserController browserController) {
        return new FieldsFixture(browserController) {
            @Override
            public void execute() throws Exception {
                this.currentElement().clear();
                this.currentElement().sendKeys(value);
            }
        };
    }

    public static FieldsFixture checkFields(org.fitweb.drivers.BrowserController browserController) {
        return new FieldsFixture(browserController) {};
    }

    private FieldsFixture(BrowserController controller) {
        this.controller = controller;
    }

    @Override
    public void doRow(Parse row) {
        super.doRow(row);
        if (valueMatches()) {
            right(row);
        } else {
            wrong(row);
        }
    }

    protected WebElement currentElement() {
        return controller.findElement(By.xpath("//input[@name='" + name + "']"));
    }

    private boolean valueMatches() {
        String actualValue = this.currentElement().getValue();
        return actualValue != null && actualValue.equals(value);
    }
}
